# appendix A

# JavaScript Structure and Objects Reference

CONTENTS

- Built-In Objects
  - `Array`
  - `String`
  - `Math`
  - `Date`
  - `navigator`
- The JavaScript Object Hierarchy
  - `window`
  - `location`
  - `history`
  - `document`
- Creating and Customizing Objects
  - Creating Objects
  - Customizing Objects

This appendix is a quick reference for JavaScript objects. It includes the built-in objects and the objects in the object hierarchy. For further information, refer to Part II, "Using JavaScript Objects and Forms," of this book.

## Built-In Objects

The following objects are built in to JavaScript. Some can be used to create objects of your own; others can be used only as they are. Each is summarized in the following sections. See Chapter 4, "Using Built-In Objects and Custom Objects," for details and examples.

### `Array`

You can create a new `Array` object to define an array-a numbered list of variables. (Unlike other variables, arrays must be declared.) Use the `new` keyword to define an array, as in this example:

>     students = new Array(30)

Items in the array are indexed beginning with `0`. Refer to items in the array with brackets:

>     fifth = students[4];

Arrays have a single property, `length`, which gives the current number of elements in the array. They have the following methods:

- `join` quickly joins all the array's elements together, resulting in a string. The elements are separated by commas, or by the separator you specify.
- `reverse` returns a reversed version of the array.
- `sort` returns a sorted version of the array. Normally, this is an alphabetical sort; however, you can use a custom sort method by specifying a comparison routine.

### `String`

Any string of characters in JavaScript is a `string` object. The following statement assigns a variable to a string value:

>     text = "This is a test."

Because strings are objects, you can also create a new string with the `new` keyword:

>     text = new String("This is a test.");

`string` objects have a single property, `length`, which reflects the current length of the string. There are a variety of methods available to work with strings:

- `anchor()` creates an HTML anchor within the current page.
- `indexOf()` finds an occurrence of a string within the string.
- `lastIndexOf()` finds an occurrence of a string within the string, starting at the end of the string.
- `link()` creates an HTML link using the string's text.
- `split()` splits the string into an array based on a separator.
- `substring()` returns a portion of the string.
- `toString()` can be used on non-string values and converts them to strings.
- `toUpperCase()` converts all characters in the string to uppercase.
- `toLowerCase()` converts all characters in the string to lowercase.

There are also a few methods that enable you to change a string's appearance when it appears in an HTML document:

- `big()` displays big text, using the `<BIG>` tag in HTML 3.0.
- `blink()` displays blinking text, using the `<BLINK>` tag in Netscape.
- `bold()` displays bold tag, using the `<B>` tag.
- `fixed()` displays fixed-font text, using the `<TT>` tag.
- `fontcolor()` displays the string in a colored font, equivalent to the `<FONTCOLOR>` tag in Netscape.
- `fontsize()` changes the font size, using the `<FONTSIZE>` tag in Netscape.
- `italics()` displays the string in italics, using the `<I>` tag.
- `small()` displays the string in small letters using the `<SMALL>` tag in HTML 3.0.
- `strike()` displays the string in a strikethrough font, using the `<STRIKE>` tag.
- `sub()` displays subscript text, equivalent to the `<SUB>` tag in HTML 3.0.
- `sup()` displays superscript text, equivalent to the `<SUP>` tag in HTML 3.0.

As an example, this statement prints the value of the `text` string in italics:

>     document.write(text.italics());

### `Math`

The `Math` object is not a "real" object, because you can't create your own objects. Each property or method uses the built-in `Math` object. A variety of mathematical constants are available as properties of the `Math` object:

- `Math.E` is the base of natural logarithms (approximately 2.718).
- `Math.LN2` is the natural logarithm of two (approximately 0.693).
- `Math.LN10` is the natural logarithm of 10 (approximately 2.302).
- `Math.LOG2E` is the base 2 logarithm of e (approximately 1.442).
- `Math.LOG10E` is the base 10 logarithm of e (approximately 0.434).
- `Math.PI` is the ratio of a circle's circumference to its diameter (approximately 3.14159).
- `Math.SQRT1_2` is the square root of one-half (approximately 0.707).
- `Math.SQRT2` is the square root of two (approximately 2.7178).

The methods of the `Math` object enable you to perform mathematical functions. The methods are listed in the following sections in categories.

#### Algebraic Functions

- `Math.acos()` calculates the arc cosine of a number, in radians.
- `Math.asin()` calculates the arc sine of a number.
- `Math.atan()` calculates the arc tangent of a number.
- `Math.atan2()` calculates the polar coordinate angle (theta) for an `x`, `y` coordinate pair.
- `Math.cos()` calculates the cosine of a number.
- `Math.sin()` returns the sine of a number.
- `Math.tan()` calculates the tangent of a number.

#### Statistical and Logarithmic Functions

- `Math.exp()` returns `e` (the base of natural logarithms) raised to a power.
- `Math.log()` returns the natural logarithm of a number.
- `Math.max()` accepts two numbers and returns whichever is greater.
- `Math.min()` accepts two numbers and returns the smaller of the two.

For example, this statement assigns the `big` variable to the larger of `x` and `y`:

>     big = Math.max(x,y);

#### Basic Math and Rounding

- `Math.abs()` calculates the absolute value of a number.
- `Math.ceil()` rounds a number up to the nearest integer.
- `Math.floor()` rounds a number down to the nearest integer.
- `Math.pow()` calculates one number to the power of another.
- `Math.round()` rounds a number to the nearest integer.
- `Math.sqrt()` calculates the square root of a number.

As an example, the following statement assigns the `x` variable to the square root
of 35:

>     x = Math.sqrt(25);

#### Random Numbers

`Math.random()` returns a random number between 0 and 1.

Note
The `Math.random()` method worked only on UNIX platforms until Netscape 3.0. Be sure you and your users use the latest version.

### `Date`

The `Date` object is a built-in JavaScript object that enables you to work conveniently with dates and times. You can create a `Date` object any time you need to store a date and use the `Date` object's methods to work with the date:

Note
The `Date` object will not work with dates before January 1st, 1970.

- `setDate()` sets the day of the month.
- `setMonth()` sets the month. JavaScript numbers the months from 0 to 11, starting with January (0).
- `setYear()` sets the year.
- `setTime()` sets the time (and the date) by specifying the number of milliseconds since January 1st, 1970.
- `setHours()`, `setMinutes()`, and `setSeconds()` set the time.
- `getDate()` gets the day of the month.
- `getMonth()` gets the month.
- `getYear()` gets the year.
- `getTime()` gets the time (and the date) as the number of milliseconds since January 1st, 1970.
- `getHours()`, `getMinutes()`, and `getSeconds()` get the time.
- `getTimeZoneOffset()` gives you the local time zone's offset from GMT.
- `toGMTString()` converts the date object's time value to text, using GMT (Greenwich Mean Time, also known as UTC).
- `toLocalString()` converts the date object's time value to text, using the user's local time.
- `Date.parse()` converts a date string, such as `"June 20, 1996"` to a `Date` object (number of milliseconds since 1/1/1970).
- `Date.UTC()` is the opposite; it converts a `Date` object value (number of milliseconds) to a UTC (GMT) time.

### `navigator`

The `navigator` object includes information about the current browser version. At present, it works only with Netscape browsers. Its properties include the following:

- `navigator.appcodeName` is the browser's code name, usually `"Mozilla"`.
- `navigator.appName` is the browser's name, usually `"Netscape"`.
- `navigator.appVersion` is the version of Netscape being used. Example: `"3.0(Win95;I)"`.
- `navigator.userAgent` is the user-agent header, which is sent to the host when requesting a Web page. It includes the entire version information-for example, `"Mozilla/2.0(Win95;I)"`.
- `navigator.javaEnabled` is either `true` or `false`, indicating whether Java (not JavaScript) is enabled on the browser.
- `navigator.plugins` is an array that contains information about each currently available plug-in (see Chapter 13, "Working with Multimedia and Plug-Ins).
- `navigator.mimeTypes` is an array containing an element for each of the available MIME types (see Chapter 13).

## The JavaScript Object Hierarchy

The object hierarchy includes objects that represent the browser window, the current document, and its contents. These objects are summarized here and explained in detail in Chapter 5 "Accessing Window Elements as Objects."

### `window`

The `window` object represents the current browser window. If multiple windows are open or frames are used, there may be more than one window object. These are given aliases to distinguish them:

- `self` is the current window, as is `window`. This is the window containing the current JavaScript document.
- `top` is the window currently on top (active) on the screen.
- `parent` is a window that contains frames. Each frame is also a `window` object under `parent`.
- Within a window you have created, `opener` refers to the window that opened the window.
- The `frames` array contains the `window` object for each frame. These can be addressed as `parent.frames[0]` through the number of frames, or with their individual names, as in `parent.docframe`.

Each `window` object includes the following properties:

- `defaultStatus` is the initial message displayed in the status line.
- `length` is the number of frames within a parent window.
- `name` is the name of the window.
- `status` is the current value of the status line.

The `window` object also has three child objects, which you'll look at in their own sections later:

- The `location` object stores the location (URL) of the document displayed in the window.
- The `document` object holds the Web page itself.
- The `history` object contains a list of sites visited before or after the current site in the window.

The `window` object includes the following methods:

- `alert()` displays an alert dialog.
- `blur()` removes focus from the window, sending it to the background.
- `close()` closes a window you have opened.
- `confirm()` displays a confirmation dialog and returns `true` or `false`.
- `focus()` gives the window focus, moving it to the top.
- `open()` opens a new window.
- `prompt()` prompts the user and returns the text entered.
- `scroll()` scrolls the window, either horizontally or vertically. The parameters are `x` and `y` (column and row) offset in pixels.
- `setTimeout()` sets a timeout to execute a statement and returns an identifier for the timeout.
- `clearTimeout()` clears the timeout you specify.

Finally, `window` objects have the following event handlers, which you can define in the document's `<BODY>` or `<FRAMESET>` tag:

- The `onLoad` event occurs when the document in the window is finished loading.
- The `onUnload` event occurs when another document starts to load, replacing the window's current document.
- The `onFocus` event occurs when the window receives focus.
- The `onBlur` event occurs when the window loses focus.
- The `onError` event occurs if the document in the window fails to load properly.

### `location`

The `location` object contains information about the current URL being displayed by the window. It has a set of properties to hold the different components of the URL:

- `location.protocol` is the protocol (or method) of the URL.
- `location.hostname` specifies the host name.
- `location.port` specifies the communication port.
- `location.host` is a combination of the host name and port.
- `location.pathname` is the directory to find the document on the host, and the name of the file.
- `location.hash` is the name of an anchor within the document, if specified.
- `location.target` specifies the `TARGET` attribute of the link that was used to reach the current location.
- `location.query` specifies a query string.
- `location.href` is the entire URL.

The `location` object also has two methods:

- `location.reload()` reloads the current document; this is the same as the reload button on Netscape's toolbar.
- `location.replace()` replaces the current location with a new one; this is similar to setting the `location` object's properties.

### `history`

The `history` object holds information about the URLs that have been visited before and after the current one in the window, and it includes methods to go to previous or next locations:

- `history.back()` goes back to the previous location.
- `history.forward()` goes forward to the next location.
- `history.go()` goes to a specified offset in the history list (negative numbers go back, positive numbers go forward).

### `document`

The `document` object represents the current document in the window and is a child of the `window` object. It includes the following properties:

- `bgColor` is the background color, specified with the `BGCOLOR` attribute.
- `fgColor` is the foreground (text) color, specified with the `TEXT` attribute.
- `lastModified` is the date the document was last modified. This date is sent from the server along with the page.
- `linkColor` is the color used for nonvisited links, specified with the `LINK` attribute.
- `location` specifies the document's URL. Don't confuse this with the `window.location` object.
- `referrer` is the URL of the page the user was viewing prior to the current page-usually, the page with a link to the current page.
- `title` is the title of the current page, defined by the HTML `<TITLE>` tag.
- `vlinkColor` is the color for visited links, specified with the `VLINK` attribute.

The `document` object also includes the following child objects as properties:

- `document.forms` is an array with an element for each form in the document. These can also be addressed by name, as in `document.regform`. Form elements are child objects of the form object and are described in Chapter 6 "Using Interactive Forms."
- `document.links` is an array containing elements for each of the links in the document. It can also contain `area` objects, used for client-side image maps.
- `document.anchors` is an array with elements for each of the anchors in the document.
- `document.images` contains an element for each of the images in the current document. Chapter 12, "Working with Graphics and Games," explains this object in detail.
- `document.applets` is an array with references to each embedded Java applet in the document. This object is explained in Chapter 16, "Integrating JavaScript with Java."

The `document` object has no event handlers. It includes the following methods:

- `clear()` clears a document you have closed.
- `close()` closes a stream and displays any text you have written.
- `open()` opens a stream and clears the current document.
- `write()` writes text to the document window.
- `writeln()` writes text to the document window and adds a carriage return.

## Creating and Customizing Objects

This is a brief summary of the keywords you can use to create your own objects and customize existing objects. These are documented in detail in Chapter 4 "Using Built-In Objects and Custom Objects."

### Creating Objects

There are three JavaScript keywords used to create and refer to objects:

- `new` is used to create a new object.
- `this` is used to refer to the current object. `this` can be used in an object's constructor function or in an event handler.
- `with` makes an object the default for a group of statements. Properties without complete object references will refer to this object.

To create a new object, you need an object constructor function. This simply assigns values to the object's properties using `this`:

>     function Name(first,last) {
>        this.first = first;
>        this.last = last;
>     }

You can then create a new object using `new`:

>     Fred = new Name("Fred","Smith");

You can also create a generic object using the `Object()` constructor and define its properties later:

>     values = new Object();

### Customizing Objects

You can add additional properties to an object you have created just by assigning them:

>     Fred.middle = "Clarence";

Properties you add this way apply only to that instance of the object, not to all objects of the type. A more permanent approach is to use the `prototype` keyword, which adds a property to an object's prototype (definition). This means that any future object of the type will include this property. You can include a default value:

>     Name.prototype.title = "Citizen";

You can use this technique to add properties to the definitions of built-in objects as well. For example, this statement adds a property called `num` to all existing and future string objects, with a default value of 10:

>     string.prototype.num = 10;